package com.vf.s.common.plugins.shiro;

import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.log.Log;
import com.vf.core.render.RenderBean;

public class ShiroInterceptor implements Interceptor {
	
	protected final Log LOG = Log.getLog(getClass());
	
	public void intercept(Invocation ai) {
		AuthzHandler ah = ShiroKit.getAuthzHandler(ai.getActionKey());
		Controller  controller = ai.getController();
		if (ah != null) {
			try {
				LOG.debug("执行权限检查");
				ah.assertAuthorized();
			}catch (UnauthenticatedException lae) {
				if(isAjaxRequest(controller.getRequest())) {
					LOG.debug("身份验证失败，ajax请求，返回json数据.");
					RenderBean renderBean=new RenderBean();
					renderBean.setCode(403);
					renderBean.setMessage("请先登录!");
					renderBean.setData(ai.getController().getRequest());
					controller.renderJson(renderBean);
				}
				else{
					LOG.debug("身份验证失败，非ajax请求，返回html.");
					controller.redirect(ShiroKit.getLoginUrl());
				}
				return;
			} catch (AuthorizationException ae) {
				if(isAjaxRequest(controller.getRequest())){
					LOG.debug("没有权限访问，ajax请求，返回json数据.");
					RenderBean renderBean=new RenderBean();
					renderBean.setCode(403);
					renderBean.setMessage("请先登录!");
					renderBean.setData(ai.getController().getRequest());
					controller.renderJson(renderBean);
				}else{
					LOG.debug("没有权限访问，非ajax请求，返回html.");
					controller.redirect(ShiroKit.getUnauthorizedUrl());
				}
				return;
			}
		}else {
			if(isAjaxRequest(controller.getRequest())) {
				RenderBean renderBean=new RenderBean();
				renderBean.setCode(404);
				renderBean.setMessage("无效路由404!");
				renderBean.setCode(40004);
				renderBean.setData(ai.getController().getRequest());
				
			}else {
				ai.getController().redirect(ShiroKit.getLoginUrl());
			}
		}
	}
	
	public static boolean isAjaxRequest(HttpServletRequest request) {
		String requestedWith = request.getHeader("x-requested-with");
		if (requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest")) {
			return true;
		} else {
			return false;
		}
	}
	
}
